<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>虚拟列表-不定高</title>
    <style>
      #list {
        padding: 0;
        margin: 0;
        list-style: none;
      }

      .list-item {
        padding: 10px;
        border-bottom: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <main>
      <!-- <h1 style="text-align: center">虚拟列表-不定高</h1> -->
      <div id="list-container" style="height: 600px; overflow-y: auto">
        <ul id="list">
          <!-- 列表项将动态插入这里 -->
        </ul>
        <!-- 观察节点 -->
        <div id="sentinel"></div>
      </div>
    </main>
  </body>
  <script>
    const arr = Array.from({ length: 1000 }, (_, i) => i); // 假设有1000条数据
    const observer = new IntersectionObserver(
      (entries, observer) => {
        entries.forEach((entry) => {
          console.log("entry", entry);
          // 处理每个 entry 对象
          if (entry.isIntersecting) {
            console.log("Element is visible");
          } else {
            console.log("Element is not visible");
          }
        });
      },
      {
        root: document.getElementById("list-container"),
      },
    );

    console.log("observer", observer);

    const listContainer = document.getElementById("list-container");
    const list = document.getElementById("list");
    const sentinel = document.getElementById("sentinel");
    const batchSize = 20;

    // 添加新的不定高项目到列表中
    const renderList = (start, end) => {
      for (let i = start; i <= end && i < arr.length; i++) {
        const item = document.createElement("li");
        item.classList.add("list-item");
        item.textContent = `Item ${i}`;
        Object.assign(item.style, {
          // 高度随机，背景颜色随机
          height: `${Math.floor(Math.random() * 200) + 100}px`,
          background: `hsl(${Math.floor(Math.random() * 360)}, 50%, 50%)`,
        });
        list.appendChild(item);
        observer.observe(item);
      }
    };

    renderList(0, 10);
  </script>
</html>
